from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.core.urlresolvers import reverse

# Create your views here.
# 数据分页模块
from django.core.paginator import Paginator
from .. import models

# 商品分类 添加
def catesadd(request):

    if request.method == 'GET':
        # 获取所有商品分类数据
        data = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
        # 分配数据
        context = {'cateslist':data}
        # 加载模板
        return render(request,'myadmin/cates/add.html',context)

    elif request.method == 'POST':
        try:
            # 执行添加
            db = models.Cates()
            db.name = request.POST.get('name')
            db.pid = request.POST.get('pid')
            # print(db.pid)
            # 判断是否为顶级分类
            if db.pid == '0':
                db.path = '0,'
                db.save()
                return HttpResponse('<script>alert("添加成功");location.href="'+reverse('myadmin_cates_index')+'"</script>')
            else:
                # 获取当前所选的分类的path
                fdb = models.Cates.objects.get(id=db.pid)
                db.path = fdb.path + db.pid + ','
                # print(db.path)
                num = db.path.count(',')
                print(num)
                if num <= 4:
                    db.save()       
                    return HttpResponse('<script>alert("添加成功");location.href="'+reverse('myadmin_cates_index')+'"</script>')
                else:
                    return HttpResponse('<script>alert("商品分类只设置四级，当前设置超过四级，添加失败！");location.href="'+reverse('myadmin_cates_add')+'"</script>')

        except:
            return HttpResponse('<script>alert("添加失败");location.href="'+reverse('myadmin_cates_add')+'"</script>')

# 商品分类 显示
def catesindex(request):
    
    # 获取所有商品分类数据
    # data = models.Cates.objects.all()
    data = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
    # print(data)
    
    # 获取搜索条件,和参数
    keywords = request.GET.get('keywords')

    # 判断是否有搜索条件
    if keywords:          
        data = data.filter(name__contains=keywords)

    # 实例化分页对象
    paginator = Paginator(data,10)

    # 获取当前页码数  ?p=n
    p = request.GET.get('p',1)

    # 获取当前页的数据
    cateslist = paginator.page(p)

    # 分配数据
    context = {'cateslist':cateslist}

    return render(request,'myadmin/cates/index.html',context)

# 商品分类 删除
def catesdel(request):
    # 获取删除商品分类的id
    cid = request.GET.get('cid')

    # 判断当前类下是否还有子类
    num = models.Cates.objects.filter(pid=cid).count()

    if num:
        return JsonResponse({'error':1,'msg':'当前分类下还有子类，不可删除！'})

    # 再确认当前类下是否右商品发布

    # 获取分类对象
    db = models.Cates.objects.get(id=cid)
    db.delete()

    return JsonResponse({'error':0,'msg':'此商品分类删除成功！'})

# 商品分类 修改
def catesedit(request):

    # 根据cid获取分类对象
    db = models.Cates.objects.get(id = request.GET.get('cid'))
    db.name = request.GET.get('name')
    db.save()
    return JsonResponse({'error':0,'msg':'分类名修改成功！'})